package com.github.catvod.spider;

import android.text.TextUtils;

import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.utils.Misc;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 适配91-JAV
 *
 * @Author zlliu
 * @Date 2025/8/26
 * @Description
 */
public class XPath91 extends XPathV2 {

    protected String categoryUrl(String tid, String pg, boolean filter, HashMap<String, String> extend) {
        if (extend != null && !extend.isEmpty()) {
            for (String key : extend.keySet()) {
                String value = extend.get(key);
                if (StringUtils.isNotBlank(value)) {
                    value = value.replace("{catePg}", pg);
                    //  此处地址的拼接与XPathV2不同
                    return rule.getHomeUrl() + "/" + value;
                }
            }
        }
        return getCateUrl(true).replace("{cateId}", tid).replace("{catePg}", pg);
    }

    @Override
    public String detailContent(List<String> ids) {
        try {
            fetchRule();
            String webUrl = getDetailUrl(true).replace("{vid}", ids.get(0));
            String webContent = fetch(webUrl);
            JXDocument doc = JXDocument.create(webContent);

            String cover = "", title = "", desc = "", category = "", area = "", year = "", remark = "", director = "", actor = "";

            title = doc.selNOne(rule.getDetailName()).asString().trim();

            //  通过script获得
            JXNode script = doc.selNOne("//script[@type=\"application/ld+json\"]/text()");
            JSONObject jsonObj = new JSONObject(script.asString());
            cover = jsonObj.getString("thumbnailUrl");
//            cover = doc.selNOne(rule.getDetailImg()).asString().trim();
            cover = Misc.fixUrl(webUrl, cover);

            if (StringUtils.isNotBlank(rule.getDetailCate())) {
                try {
                    category = doc.selNOne(rule.getDetailCate()).asString().trim();
                    category = rule.getDetailCateR(category);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailYear())) {
                try {
                    year = doc.selNOne(rule.getDetailYear()).asString().trim();
                    year = rule.getDetailYearR(year);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailArea())) {
                try {
                    area = doc.selNOne(rule.getDetailArea()).asString().trim();
                    area = rule.getDetailAreaR(area);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailMark())) {
                try {
                    remark = doc.selNOne(rule.getDetailMark()).asString().trim();
                    remark = rule.getDetailMarkR(remark);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailActor())) {
                try {
                    actor = doc.selNOne(rule.getDetailActor()).asString().trim();
                    actor = rule.getDetailActorR(actor);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailDirector())) {
                try {
                    director = doc.selNOne(rule.getDetailDirector()).asString().trim();
                    director = rule.getDetailDirectorR(director);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }
            if (StringUtils.isNotBlank(rule.getDetailDesc())) {
                try {
                    desc = doc.selNOne(rule.getDetailDesc()).asString().trim();
                    desc = rule.getDetailDescR(desc);
                } catch (Exception e) {
                    SpiderDebug.log(e);
                }
            }

            JSONObject vod = new JSONObject();
            vod.put("vod_id", ids.get(0));
            vod.put("vod_name", title);
            vod.put("vod_pic", cover);
            vod.put("type_name", category);
            vod.put("vod_year", year);
            vod.put("vod_area", area);
            vod.put("vod_remarks", remark);
            vod.put("vod_actor", actor);
            vod.put("vod_director", director);
            vod.put("vod_content", desc);

            ArrayList<String> playFrom = new ArrayList<>();
            playFrom.add(rule.getDetailFromName());

            ArrayList<String> playList = new ArrayList<>();
            List<String> vodItems = new ArrayList<>();
            String name = rule.getDetailUrlName().trim();
            name = rule.getDetailUrlNameR(name);

            //  从js脚本中得到m3u8地址
            JXNode scriptNode = doc.selNOne("//script[contains(text(),'var hlsUrl')]/text()");
            String scriptStr = scriptNode.asString().replaceAll("\n\r", "");
            Matcher matcher = Pattern.compile("var hlsUrl = (\".*?\");").matcher(scriptStr);
            String id = "";
            if (matcher.find()) {
                String idStr = matcher.group(1);
                id = idStr.replace("\"", "");
            }
            id = rule.getDetailUrlIdR(id);
            vodItems.add(name + "$" + id);
            playList.add(TextUtils.join("#", vodItems));

            // 排除播放列表为空的播放源
            for (int i = playFrom.size() - 1; i >= 0; i--) {
                if (playFrom.get(i).isEmpty()) {
                    playFrom.remove(i);
                }
            }
            for (int i = playList.size() - 1; i >= 0; i--) {
                if (playList.get(i).isEmpty()) {
                    playList.remove(i);
                }
            }
            for (int i = playList.size() - 1; i >= 0; i--) {
                if (i >= playFrom.size()) {
                    playList.remove(i);
                }
            }
            String vod_play_from = TextUtils.join("$$$", playFrom);
            String vod_play_url = TextUtils.join("$$$", playList);
            vod.put("vod_play_from", vod_play_from);
            vod.put("vod_play_url", vod_play_url);

            detailContentExt(webContent, vod);

            JSONObject result = new JSONObject();
            JSONArray list = new JSONArray();
            list.put(vod);
            result.put("list", list);
            return result.toString();
        } catch (Exception e) {
            SpiderDebug.log(e);
        }
        return "";
    }

    @Override
    protected String getPlayUrl(boolean append) {
        return super.getPlayUrl(false);
    }

    @Override
    protected boolean nodeSkip(JXNode node) {
        //  跳过广告节点：
        //  xpath: //span[contains(text(),'广告')]
        JXNode jxNode = node.selOne("//span[contains(text(),'广告')]");
        if (jxNode != null) {
            return true;
        }
        return super.nodeSkip(node);
    }
}